package com.anxin.act.task.service;

import com.alibaba.fastjson.JSONObject;
import com.anxin.act.task.entity.ViewHiTask;
import com.anxin.act.task.entity.ViewRuTask;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.utils.DateUtils;
import com.anxin.common.utils.http.HttpUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.security.entity.SysTempToken;
import com.anxin.sys.system.entity.SysConfig;
import com.anxin.sys.system.entity.SysUser;
import com.anxin.sys.system.utils.ConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 泛微待办对接
 */
@Service
public class ActDockingWeaverSendService implements ActDockingSend {
    private static Logger logger = LoggerFactory.getLogger("sys-info");

    /**
     * 对接发送待办
     * @param viewRuTask
     * @param userId
     * @param userName
     */
    public void sendTodoTask(SysTempToken sysTempToken,ViewRuTask viewRuTask, String userId, String userName){
        Map<String, Object> processVar = ActUtils.getProcessVar(viewRuTask.getActId());

        String userCode = UserUtils.getUser(userId).getUserKey();
//        logger.info("发送代办的接收人usercode："+userCode);
        // 是否加急
        String urgent = (processVar.get("urgent") != null && "N".equals(processVar.get("urgent").toString())) ? "0" : "1";

        //根据流程id  获取属于那个项目下
        boolean isFlag = false;

        JSONObject param = new JSONObject();
        // 系统标识
        param.put("syscode",ConfigUtils.get("todoDockingSysCode"));
        // 流程实例ID
        param.put("flowid",viewRuTask.getId());
        // 流程标题
        param.put("requestname",processVar.get("title"));
        // 流程名称
        param.put("workflowname","投资系统待办流程");
        // 步骤名称
        param.put("nodename",viewRuTask.getTaskName());
        // PC地址
        param.put("pcurl",sysTempToken.getUseUrl());
        // APP地址
        param.put("appurl",sysTempToken.getUseUrl());
        // 流程处理状态 0：待办 2：已办 4：办结 8：抄送（待阅）
        param.put("isremark","0");
        // 流程查看状态 0：未读 （注：isremark = 0 且 viewtype = 0 会给OA消息中心推送消息，对接钉钉、企业微信） 1：已读;\
        param.put("viewtype","0");
        // 加急程度
        param.put("requestlevel",urgent);
        // 创建人
        param.put("creator",processVar.get("applyUserName"));
        // 创建日期
        param.put("createdatetime", DateUtils.format( "yyyy-MM-dd HH:mm:ss", new Date(Long.parseLong(processVar.get("applyTime").toString()))));
        // 接收人
        param.put("receiver",userCode);
        // 接受日期时间
        param.put("receivedatetime",DateUtils.format("yyyy-MM-dd HH:mm:ss", viewRuTask.getStartTime()));
        // 时间戳字段，客户端使用线程调用接口的时候，根据此字段判断是否需要更新数据，防止后发的请求数据被之前的覆盖 例如"1602817491990"(毫秒级时间戳)
        param.put("receivets",System.currentTimeMillis());

        String url = ConfigUtils.get(ConfigUtils.get("todoDockingSysCode")) + "/rest/ofs/ReceiveRequestInfoByJson";
        logger.info("推送待办到泛微报文===============>" + param);
        String res = HttpUtils.postSendHttpJson(url, param.toJSONString());
        logger.info("推送待办泛微返回报文===============>" + res);
    }

    /**
     * 对接删除待办
     * @param actId
     * @param taskId
     * @param userId
     * @param userName
     */
    public void delTodoTask(String actId,String taskId,String userId,String userName){
        SysUser sysuser = UserUtils.getUserByUserName(userName);
        String userCode = sysuser.getUserKey();

        JSONObject param = new JSONObject();
        // 系统标识
        param.put("syscode","TZXT");
        // 任务ID
        param.put("flowid",taskId);
        // 用户标识
        param.put("userid",userCode);

        String url = ConfigUtils.get("fw_url") + "/rest/ofs/deleteUserRequestInfoByJson";
        logger.info("删除待办到泛微推送参数===============>" + param);
        String res = HttpUtils.postSendHttpJson(url, param.toJSONString());
        logger.info("删除待办到泛微返回报文===============>" + res);

    }

    @Override
    public void updateTodoTask(String actId, String taskId, String userId, String userName) {

    }

    /**
     * 对接发送已办
     * @param viewHiTask
     * @param userId
     * @param userName
     */
    public void sendHiTask(ViewHiTask viewHiTask,String userId,String userName){
        String usercode = UserUtils.getUser(userId).getUserKey();
//        logger.info("发送已办的接收人的userKey:"+usercode);
        Map<String, Object> processVar = ActUtils.getProcessVar(viewHiTask.getActId());


            // 为验证环境 继续执行
            String pcurl =
                    "zyt/fwTaskTodo?taskId="
                            + viewHiTask.getId()
                            + "&userId="
                            + usercode
                            + "&title="
                            + viewHiTask.getTitle()+"&actId="+viewHiTask.getActId();
            String appurl="zyt/fwTaskTodo?taskId="+viewHiTask.getId()+"&userId="+usercode+"&title="+viewHiTask.getTitle()+"&actId="+viewHiTask.getActId();

            //推送待办
            String param="{\"syscode\":\"TZXT\"," +  //异构系统标识
                    "\"flowid\":\""+viewHiTask.getId()+"\"," +         //流程实例id
                    "\"requestname\":\""+viewHiTask.getTitle()+"\"," +//标题
                    "\"workflowname\":\"投资系统待办流程\"," +//流程类型名称
                    "\"nodename\":\""+viewHiTask.getTaskName()+"\"," +//步骤名称（节点名称）
                    "\"pcurl\":\""+pcurl+"\"," +//PC地址
                    "\"appurl\":\""+appurl+"\"," +//APP地址
                    "\"isremark\":\""+2+"\"," +//流程处理状态0：待办 2：已办 4：办结 8：抄送（待阅）
                    "\"viewtype\":\""+0+"\"," +//流程查看状态  0：未读 1：已读;
                    "\"creator\":\""+processVar.get("applyUserName")+"\","+//创建人（原值）
                    "\"createdatetime\":\""+
                    DateUtils.format(
                            "yyyy-MM-dd HH:mm:ss",
                            new Date(Long.parseLong(processVar.get("applyTime").toString())))
                    +//创建日期时间
                    "\"," +
                    "\"receiver\":\""+usercode+"\"," +//接收人（原值）
                    "\"receivedatetime\":\""+
                    DateUtils.format("yyyy-MM-dd HH:mm:ss", viewHiTask.getStartTime())
                    +"\"," +//接收日期时间
                    "\"receivets\":\""+System.currentTimeMillis()+"\"" +//时间戳字段
                    "}";
            //        String url="http://121.40.182.240:8080/rest/ofs/ReceiveRequestInfoByJson";
            String url= ConfigUtils.get("fw_url")+"/rest/ofs/ReceiveRequestInfoByJson";
//            logger.info("推送已办到泛微报文===============>" + param);
            System.out.println("推送已办到泛微报文===============>"+param);
            String res = HttpUtils.postSendHttpJson(url, param);
            logger.info("推送已办到泛微报文===============>" + res);
            System.out.println("推送已办泛微返回报文===============>" + res);
    }

    /**
     * 对接删除已办
     * @param viewHiTask
     * @param userId
     * @param userName
     */
    public void delHiTask(ViewHiTask viewHiTask,String userId,String userName){

    }

}
